from fastapi import APIRouter, Body
from pydantic import BaseModel
from app.engine.backtest_engine import run_backtest
import time

router = APIRouter()

class BacktestRequest(BaseModel):
    code: str
    start_date: str
    end_date: str
    strategy_name: str
    initial_cash: float = 100000.0
    position_sizer: int = 95
    commission_rate: float = 0.0003
    # asset_type is removed as it's now auto-detected

@router.post("/")
async def start_backtest(request: BacktestRequest = Body(...)):
    """
    接收前端的回测请求，并调用回测引擎执行。
    """
    start_time = time.time()
    print(f"\n=== 收到回测请求 ===")
    print(f"请求时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"股票代码: {request.code}")
    print(f"回测周期: {request.start_date} 至 {request.end_date}")
    print(f"策略名称: {request.strategy_name}")
    print(f"初始资金: {request.initial_cash}")
    print(f"仓位比例: {request.position_sizer}%")
    print(f"佣金费率: {request.commission_rate}")
    
    try:
        result = run_backtest(
            code=request.code,
            start_date=request.start_date,
            end_date=request.end_date,
            strategy_name=request.strategy_name,
            initial_cash=request.initial_cash,
            position_sizer=request.position_sizer,
            commission_rate=request.commission_rate,
            # asset_type is no longer passed
        )
        
        end_time = time.time()
        print(f"=== 回测请求完成 ===")
        print(f"总耗时: {end_time - start_time:.2f}秒")
        print(f"返回结果: {'成功' if 'error' not in result else '失败'}")
        
        return result
        
    except Exception as e:
        end_time = time.time()
        error_msg = f"回测执行过程中发生异常: {str(e)}"
        print(f"✗ {error_msg}")
        print(f"异常详情: {e}")
        print(f"总耗时: {end_time - start_time:.2f}秒")
        return {"error": error_msg} 